<template>
    <a-modal v-model="visible" :title="title" :confirmLoading="submitLoading" width="1000px" ok-text="确认" cancel-text="取消" @ok="addFormSubmit">
        <a-form layout="vertical" :form="events_form">
            <a-card title="账号信息" style="margin-bottom:24px">
                <label slot="extra" v-if="!disableds" href="#">默认密码为：a123456</label>
                <a-row :gutter="20">
                    <a-col :span="8">
                        <a-form-item label="账号名称（创建后不能修改）">
                            <a-input :disabled="disableds" v-decorator="['accountName', { rules: [{ required: true, message: '请输入园区名称' }] }]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="联系方式">
                            <a-input :maxLength="11" v-decorator="['contactPhone', { rules: [{ required: true, message: '请输入联系方式' },{
            pattern:/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/,message: '手机格式错误'}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="联系人">
                            <a-input v-decorator="['contact', { rules: [{ required: true, message: '请输入联系人' }],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="邮箱">
                            <a-input v-decorator="['email', { rules: [{ required: true, message: '请输入邮箱' },{
            pattern: /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/, message: '邮箱格式错误'}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="所在地区（支持搜索）">
                            <a-cascader placeholder="请选择地区" @change="cityChange" :show-search="{ filter }" :options="cityData" v-decorator="['areaCode',{rules: [{ required: true, message: '请选择所在地区!' }]}]" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="账号类型">
                            <a-select :disabled="disableds" v-decorator="['userTypeCode',{rules: [{ required: true, message: '请选择账号类型!' }]}]" @change="handleUserTypeChange">
                                <a-select-option v-for="userType in userTypeData" :key="userType.value">
                                    {{ userType.name }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="所属角色（账号类型关联获取）">
                            <a-select v-if="!disableds" v-decorator="['roleId',{rules: [{ required: true, message: '请选择角色!' }]}]">
                                <a-select-option v-for="role in roleData" :key="role.roleId">
                                    {{ role.roleName }}
                                </a-select-option>
                            </a-select>
                             <a-input v-if="disableds" :disabled="true" v-decorator="['roleName']"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>

            <a-card title="园区信息" style="margin-bottom:24px">
               <a-row :gutter="20">
                    <a-col :span="8">
                        <a-form-item label="法人姓名（创建后不能修改）">
                            <a-input :disabled="disableds" v-decorator="['legalPersonName', { rules: [{ required: true, message: '请输入法人姓名' }],initialValue: '' }]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="法人身份证号码（创建后不能修改）">
                            <a-input :disabled="disableds" v-decorator="['legalPersonIdCard', { rules: [{ required: true, message: '请输入法人身份证号码' },{validator: handleConfirmIdCard}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="法人手机号码（创建后不能修改）">
                            <a-input :disabled="disableds" :maxLength="11" v-decorator="['legalPersonPhone', { rules: [{ required: true, message: '请输入法人手机号码' },{
            pattern:/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/,message: '手机格式错误'}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="园区名称（创建后不能修改）">
                            <a-input :disabled="disableds" v-decorator="['name', { rules: [{ required: true, message: '请输入园区名称' }],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="纳税人性质">
                            <a-select v-decorator="['taxNature',{rules: [{ required: true, message: '请选择纳税人性质!' }],initialValue: ''}]">
                                <a-select-option v-for="role in taxData" :key="role.value">
                                    {{ role.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="社会统一代码（创建后不能修改）">
                            <a-input :disabled="disableds" v-decorator="['creditCode', { rules: [{ required: true, message: '请输入社会统一代码'},{validator: handleConfirmCreditCode}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                     <a-col :span="8">
                        <a-form-item label="银行账号（创建后不能修改）">
                            <a-input :disabled="disableds" v-decorator="['bankCard', { rules: [{ required: true, message: '请输入银行账号'},{validator: handleConfirmBankCard}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="银行预留手机号码">
                            <a-input :maxLength="11" v-decorator="['bankReservedPhone', { rules: [{
            pattern:/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/,message: '手机格式错误'}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-item label="动态口令接收手机号码（支付宝）">
                            <a-input :maxLength="11" v-decorator="['dynamicWordPhone', { rules: [{ required: true, message: '请输入动态口令接收手机号码' },{
            pattern:/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/,message: '手机格式错误'}],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="园区地址">
                            <a-textarea type="textarea" :rows="4" v-decorator="['address', { rules: [{ required: true, message: '请输入园区地址' }],initialValue: ''}]"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>
           
            <a-card title="附件信息" style="margin-bottom:24px">
                 <a-row :gutter="20">
                    <a-col :span="6">
                        <a-form-item label="资质图片" >
                            <div v-show="modifyForm.certificate">
                                <img :src="modifyForm.certificate" style="width:180px;height:120px;" />
                                <div class="certificate" v-show="false" v-viewer="{movable: false}">
                                    <img :src="modifyForm.certificate" style="width:180px;height:120px;" />
                                </div>
                                <div style="padding:5px;display:flex">
                                    <a href="#" style="padding-right:55px" @click="showDo('certificate')">查看大图</a>
                                    <a href="#" type="link" @click="uploadImg(4)">重新上传</a>
                                </div>
                            </div>
                            <div v-show="!modifyForm.certificate">
                                <a head="#" @click="uploadImg(4)">资质上传</a>
                                <input type="file" ref="certificate" @change="function (e){return handleChange(e,'certificate')}" style="display: none;" />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item label="营业执照" >
                            <div v-show="modifyForm.businessLicense">
                                <img :src="modifyForm.businessLicense" style="width:180px;height:120px;" />
                                <div class="businessLicense" v-show="false" v-viewer="{movable: false}">
                                    <img :src="modifyForm.businessLicense" style="width:180px;height:120px;" />
                                </div>
                                <div style="padding:5px;display:flex">
                                    <a href="#" style="padding-right:55px" @click="showDo('businessLicense')">查看大图</a>
                                    <a href="#" type="link" @click="uploadImg(1)">重新上传</a>
                                </div>
                            </div>
                            <div v-show="!modifyForm.businessLicense">
                                <a head="#" @click="uploadImg(1)">上传营业执照</a>
                                <input type="file" ref="businessLicense" @change="function (e){return handleChange(e,'businessLicense')}" style="display: none;" />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item label="法人身份证正面" >
                            <div v-show="modifyForm.legalPersonIdCardFront">
                                <img :src="modifyForm.legalPersonIdCardFront" style="width:180px;height:120px;" />
                                <div class="legalPersonIdCardFront" v-show="false" v-viewer="{movable: false}">
                                    <img :src="modifyForm.legalPersonIdCardFront" style="width:180px;height:120px;" />
                                </div>
                                <div style="padding:5px;display:flex">
                                    <a href="#" style="padding-right:55px" @click="showDo('legalPersonIdCardFront')">查看大图</a>
                                    <a href="#" type="link" @click="uploadImg(2)">重新上传</a>
                                </div>
                            </div>
                            <div v-show="!modifyForm.legalPersonIdCardFront">
                                <a head="#" @click="uploadImg(2)">上传法人身份证正面</a>
                                <input type="file" ref="legalPersonIdCardFront" @change="function (e){return handleChange(e,'legalPersonIdCardFront')}" style="display: none;" />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item label="法人身份证反面" >
                            <div v-show="modifyForm.legalPersonIdCardBackend">
                                <img :src="modifyForm.legalPersonIdCardBackend" style="width:180px;height:120px;" />
                                <div class="legalPersonIdCardBackend" v-show="false" v-viewer="{movable: false}">
                                    <img :src="modifyForm.legalPersonIdCardBackend" style="width:180px;height:120px;" />
                                </div>
                                <div style="padding:5px;display:flex">
                                    <a href="#" style="padding-right:55px" @click="showDo('legalPersonIdCardBackend')">查看大图</a>
                                    <a href="#" type="link" @click="uploadImg(3)">重新上传</a>
                                </div>
                            </div>
                            <div v-show="!modifyForm.legalPersonIdCardBackend">
                                <a head="#" @click="uploadImg(3)">上传法人身份证反面</a>
                                <input type="file" ref="legalPersonIdCardBackend" @change="function (e){return handleChange(e,'legalPersonIdCardBackend')}" style="display: none;" />
                            </div>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-card>
            
        </a-form>

         <a-card title="关联企业" v-if="table.loadData.length >= 1">
            <a-table :columns="table.columns" rowKey="enterpriseId" :data-source="table.loadData">
                <span slot="agreement" slot-scope="text, record" style="display: block;word-break: break-all;width: 220px;">
                    <a @click="downloadFile(record)">{{record.agreement}}</a>
                </span>
                <span slot="fees" slot-scope="text,record">
                    <div v-for="(item,index) in record.fees" :key="index">
                        【{{item.amountStart}} {{item.operator}} {{item.amountEnd}}】{{item.serviceRatio}}%
                    </div>
                </span>
            </a-table>
        </a-card>

    </a-modal>
</template>

<script>
import store from '@/store'
import { mapGetters } from 'vuex'
import { sysBaseUpload } from '@/api/manage/base'
import { 
  getSysParkAdd,
  getSysParkEdit
} from '@/api/manage/park'
import { CITY_DATA,TAX_DATA } from '@/store/mutation-types'
import { checkIDCard,CheckSocialCreditCode,previewFile} from '@/utils/util'
import {
  COLUMNS_SYS_ENTERPRISE_CONACT,
} from './form'
export default {
    name: 'sysParkForm',
    data(){
        return {
            modifyForm:{certificate:"",businessLicense:"",legalPersonIdCardFront:"",legalPersonIdCardBackend:""},
            cityData:CITY_DATA,
            taxData:TAX_DATA,
            visible:false,
            title:'',
            id:'',
            userTypeData:[],
            roleData:[],
            areaName:'',
            disableds:false,
            table:{
                columns:COLUMNS_SYS_ENTERPRISE_CONACT,
                loadData:[]
            },
            submitLoading:false
        }
    },
    beforeCreate() {
        this.events_form = this.$form.createForm(this,{name:'events_form'})
    },
    computed: {
    ...mapGetters(['userInfo'])
  },
    methods: {
    async add(rows){
        const {modifyForm} = this;
        for(var keys in modifyForm){
            modifyForm[keys] = '';
        }
        this.disableds = rows === true ? false : true;
        this.title = rows === true ? '创建园区':'编辑园区';
        this.id = rows === true ? '' : rows.id;
        this.roleData = [];
        this.userTypeData = [];
        const typeData = await store.dispatch('sysGetUserTypeData');
        const typeLabel = typeData.find(v=>v.value === 'AICTITPU18JYJ9WU6554MSZ1L3JEJS');
        this.userTypeData = [typeLabel];
        if(typeData && typeData.length >=1){
            if(rows === true){
                this.areaName = '';
                 this.$nextTick(() => {
                    this.events_form.resetFields();
                 })
                 this.visible = true;
            }else{
                this.roleData = await store.dispatch('getSysUserTypeCodeAllRole',rows.userTypeCode);
                this.modifyForm.businessLicense = rows.businessLicense;
                this.modifyForm.legalPersonIdCardFront = rows.legalPersonIdCardFront;
                this.modifyForm.legalPersonIdCardBackend = rows.legalPersonIdCardBackend;
                this.modifyForm.certificate = rows.certificate;
                this.visible = true;
                this.$nextTick(() => {
                    let values = this.events_form.getFieldsValue();
                    for(var key in values){
                        values[key] = rows[key]
                    }
                    this.events_form.setFieldsValue(values)
                });
                this.areaName = rows.area;
                this.table.loadData = rows.enterprises;
            }
        }else{
            this.$message.error('请先创建账号类型，和角色');
        }
    },
    filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    },
    cityChange(value,selectedOptions){
        if(value && value.length > 0){
            this.areaName = `${selectedOptions[0].label},${selectedOptions[1].label},${selectedOptions[2].label}`;
        }else{
            this.areaName = '';
        }
    },
    async handleUserTypeChange(keys){
        this.events_form.setFieldsValue({roleId:""});
        this.roleData = await store.dispatch('getSysUserTypeCodeAllRole',keys);
    },
    handleConfirmCreditCode(rule,value, callback){
        if (value && !CheckSocialCreditCode(value)) {
            callback('输入有误！');
        }
        callback()
    },
    handleConfirmIdCard(rule,value, callback){
         if (value && !checkIDCard(value)) {
            callback('输入有误！');
        }
        callback()
    },
    handleConfirmBankCard(rule,value, callback){
        var re = /^[0-9,]*$/;
        if (value && !re.test(value)) {
            callback('输入有误！');
        }
        callback()
    },
    //-----附件
    uploadImg(type){
        if(type === 1){
            this.$refs.businessLicense.click()
        }else if(type === 2){
            this.$refs.legalPersonIdCardFront.click()
        }else if(type === 3){
            this.$refs.legalPersonIdCardBackend.click()
        }else if(type === 4){
            this.$refs.certificate.click()
        }
    },
    async handleChange(e,filed) {
        e.preventDefault();
        let _this = this;
        let file = e.target.files[0];
        if(file===undefined){return;}
        if (file.type.indexOf('image') === -1) {
            _this.$message.error("非法图片格式");
            return;
        }
        if (!(file.size / 1024 / 1024 < 1)) {
            _this.$message.error('图片大小不能超过 1MB!')
            return;
        }
        var params = new FormData();
        params.append("file", file);
        let {code,data} = await sysBaseUpload(params);
        if (code === '1') {
            this.modifyForm[filed] = data;
        }
    },
    showDo(el) {
        const viewer = this.$el.querySelector('.'+el).$viewer
        viewer.show()
    },
    addFormSubmit(){
        let that = this;
        this.events_form.validateFieldsAndScroll(async(err, values) => {
        if (!err) {
            if(!this.modifyForm.businessLicense){
                this.$message.error('请上传营业执照');return;
            }
             if(!this.modifyForm.legalPersonIdCardFront){
                this.$message.error('请上传法人身份证正面');return;
            }
             if(!this.modifyForm.legalPersonIdCardBackend){
                this.$message.error('请上传法人身份证反面');return;
            }
            if(this.id){
                values.id = this.id;
            }
            values.certificate = this.modifyForm.certificate;
            values.area = this.areaName;
            values.areaCode = values.areaCode.join(',');
            values.businessLicense = this.modifyForm.businessLicense;
            values.legalPersonIdCardFront = this.modifyForm.legalPersonIdCardFront;
            values.legalPersonIdCardBackend = this.modifyForm.legalPersonIdCardBackend;
            that.submitLoading = true;
            const {code} = that.id ? await getSysParkEdit(values) : await getSysParkAdd(values);
            that.submitLoading = false;
            if(code === '1'){
                that.visible = false
                that.$emit('ok')
            }
        }
      });
    },
    downloadFile(row){
        previewFile(row.agreement)
    },
  }
}
</script>

